﻿/*
	Real time subtitle translate for PotPlayer (Google API)
*/

string GetTitle()
{
	return "{$CP949=구글 번역$}{$CP950=Google 翻譯$}{$CP1251=Google Переводчик$}{$CP0=Google translate$}";
}

string GetVersion()
{
	return "1";
}

string GetDesc()
{
	return "https://translate.google.com";
}

string UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";

string JsonParseOld(string json)
{
	JsonReader Reader;
	JsonValue Root;
	string ret = "";	
	if (Reader.parse(json, Root) && Root.isArray())
	{
		for (int i = 0, len = Root.size(); i < len; i++)
		{
			JsonValue child1 = Root[i];
			if (child1.isArray())
			{
				for (int j = 0, len = child1.size(); j < len; j++)
				{		
					JsonValue child2 = child1[j];
					if (child2.isArray())
					{
						JsonValue item = child2[0];
						if (!ret.empty()) ret = ret; // + "\n"
						if (item.isString()) ret = ret + item.asString();
					}
				}
				break;
			}
		}
	} 
	return ret;
}

array<string> LangTable = 
{
	"af","sq","am","ar","hy","az","eu","be","bn","bs","bg","my","ca","ceb","ny","zh",
	"zh-CN","zh-TW","co","hr","cs","da","nl","en","eo","et","tl","fi","fr","fy","gl",
	"ka","de","el","gu","ht","ha","haw","iw","hi","hmn","hu","is","ig","id","ga","it",
	"ja","jw","kn","kk","km","ko","ku","ky","lo","la","lv","lt","lb","mk","ms","mg",
	"ml","mt","mi","mr","mn","my","ne","no","ps","fa","pl","pt","pa","ro","romanji",
	"ru","sm","gd","sr","st","sn","sd","si","sk","sl","so","es","su","sw","sv","tg",
	"ta","te","th","tr","uk","ur","uz","vi","cy","xh","yi","yo","zu"
};

array<string> GetSrcLangs()
{
	array<string> ret = LangTable;
	ret.insertAt(0, ""); // empty is auto
	return ret;
}

array<string> GetDstLangs()
{
	array<string> ret = LangTable;
	return ret;
}

string Translate(string Text, string &in SrcLang, string &in DstLang)
{
	if (SrcLang.length() <= 0) SrcLang = "auto";
	SrcLang.MakeLower();
	string enc = HostUrlEncode(Text);
	string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + SrcLang + "&tl=" + DstLang + "&dt=t&q=" + enc;
	string text = HostUrlGetString(url, UserAgent);
	string ret = JsonParseOld(text);
	if (ret.length() > 0)
	{
		SrcLang = "UTF8";
		DstLang = "UTF8";
		return ret;
	}
	url = "https://translate.google.com/m?sl=" + SrcLang + "&tl=" + DstLang + "&q=" + enc;
	ret = HostUrlGetString(url, UserAgent);
	string find = "<div class=\"result-container\">";
	int s = ret.find(find);
	if (s > 0)
	{
		s = s + find.length();
		int e = ret.find("</div>", s);		
		if (e > s)
		{
			SrcLang = "UTF8";
			DstLang = "UTF8";
			return ret.substr(s, e - s); 
		}
	}
	return "";
}
